<script setup>
import { onMounted, watch, nextTick } from 'vue'
import * as d3 from 'd3'

const props = defineProps({
  data: {
    type: Array,
    required: true,
    default: () => []
  },
  width: {
    type: Number,
    default: 220
  },
  height: {
    type: Number,
    default: 280
  }
})

// 渲染饼图
const renderPieChart = () => {
  if (!d3 || !props.data || props.data.length === 0) return

  const svg = d3.select('#priceChart')
  svg.selectAll('*').remove() // 清空之前的图表

  const radius = Math.min(props.width, props.height) / 2.7
  const hoverRadius = radius * 1.1 // 鼠标悬停时的半径

  svg.attr('width', props.width)
     .attr('height', props.height)

  const g = svg.append('g')
    .attr('transform', `translate(${props.width / 2},${props.height / 3})`)

  const chartData = props.data.map(item => ({
    ...item,
    value: Number(item.value)
  }))

  const totalAmount = chartData.reduce((sum, item) => sum + item.value, 0)
  console.log('Total amount:', totalAmount)

  // 准备数据
  const finalChartData = chartData.map(item => ({
    ...item,
    percentage: totalAmount > 0 ? ((item.value / totalAmount) * 100).toFixed(1) + '%' : '0%'
  }))

  // 创建颜色比例尺
  const color = d3.scaleOrdinal()
    .domain(finalChartData.map(d => d.name))
    .range(['#3498db', '#2ecc71', '#e74c3c', '#f39c12', '#9b59b6', '#1abc9c', '#e67e22'])

  // 饼图生成器
  const pie = d3.pie()
    .value(d => d.value)
    .sort(null)

  // 弧生成器
  const arc = d3.arc()
    .innerRadius(0)
    .outerRadius(radius)

  // 悬停时的弧生成器
  const hoverArc = d3.arc()
    .innerRadius(0)
    .outerRadius(hoverRadius)

  // 标签弧生成器
  const labelArc = d3.arc()
    .innerRadius(radius * 0.7)
    .outerRadius(radius * 0.7)

  // 添加弧路径
  const arcs = g.selectAll('.arc')
    .data(pie(finalChartData))
    .enter().append('g')
    .attr('class', 'arc')

  // 添加一个提示文本容器，默认隐藏
  const tooltipText = svg.append('text')
    .attr('class', 'tooltip')
    .attr('x', props.width / 2)
    .attr('y', props.height - 10)
    .attr('text-anchor', 'middle')
    .style('fill', '#333')
    .style('font-size', '12px')
    .style('display', 'none')
    .style('font-weight', 'bold')

  arcs.append('path')
    .attr('d', arc)
    .style('fill', d => color(d.data.name))
    .style('stroke', '#fff')
    .style('stroke-width', '2px')
    .style('transition', 'all 0.3s ease')
    .on('mouseover', function(event, d) {
      // 鼠标悬停时放大
      d3.select(this)
        .style('opacity', 0.9)
        .transition()
        .duration(200)
        .attr('d', hoverArc)

      // 显示提示信息在下方
      tooltipText
        .style('display', 'block')
        .text(`${d.data.name}: ${d.data.percentage}`)
    })
    .on('mouseout', function() {
      // 鼠标离开时恢复
      d3.select(this)
        .style('opacity', 1)
        .transition()
        .duration(200)
        .attr('d', arc) // 恢复原始大小

      // 隐藏提示信息
      tooltipText.style('display', 'none')
    })

  // 添加标签
  arcs.append('text')
    .attr('transform', d => `translate(${labelArc.centroid(d)})`)
    .attr('dy', '.35em')
    .attr('text-anchor', 'middle')
    .style('font-size', '10px')
    .style('fill', '#333')
    .text(d => d.data.percentage)

  const legend = svg.append('g')
    .attr('transform', `translate(10, ${props.height - 80})`) // 将图例移到图表下方

  finalChartData.forEach((d, i) => {
    const legendRow = legend.append('g')
      .attr('transform', `translate(0, ${i * 18})`)

    legendRow.append('rect')
      .attr('width', 10)
      .attr('height', 10)
      .attr('fill', color(d.name))

    legendRow.append('text')
      .attr('x', 15)
      .attr('y', 10)
      .attr('text-anchor', 'start')
      .style('font-size', '9px')
      .text(d.name)
  })
}

watch(() => props.data, () => {
  nextTick(() => {
    renderPieChart()
  })
}, { deep: true })

// 组件挂载后渲染图表
onMounted(() => {
  nextTick(() => {
    renderPieChart()
  })
})
</script>

<template>
  <div class="pie-chart-container">
    <svg id="priceChart" style="max-width: 100%;"></svg>
  </div>
</template>

<style scoped lang="scss">
.pie-chart-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}
</style>
